package club.twelveblog.tblog.interceptor;

import club.twelveblog.tblog.common.constants.SessionConstants;
import club.twelveblog.tblog.common.enums.ExceptionEnum;
import club.twelveblog.tblog.common.exception.BlogException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 全局拦截器
 */
@Component
public class BlogInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(request.getRequestURI().startsWith("/tblog/user")){
            //获得前端传来的cookies并取得名字为token的value值
            String tokenValue = null;
            Cookie[] cookies = request.getCookies();
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals("token")) {
                    tokenValue = cookies[i].getValue();
                    break;
                }
            }
            //通过浏览器携带的tokenValue字段值，与redis缓存数据库中查找对应的key进行比对
            //得到的是关联当前用户的user_id
            //        redisTemplate.opsForValue().setIfAbsent(tokenValue);
            Boolean key = redisTemplate.hasKey(tokenValue);
            //true即为redis中存在该key,反之则反
            if (key == true) {
                //如果为真，则根据tokenValue作为key去redis获得该用户id
                SessionConstants.USER_ID = (Long) redisTemplate.opsForValue().get(tokenValue);
                return true;
            }
        }
        response.sendRedirect("请登录！！");
        return false;
    }
}
